package com.cheyunkeji.er.utils.version;

import android.Manifest;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.view.Gravity;
import android.view.View;

import com.cheyun.netsalev3.R;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.view.SDialog;
import com.cheyunkeji.er.view.SToast;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONObject;

import java.io.File;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;
import okhttp3.Call;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class UpdatePresenter implements EasyPermissions.PermissionCallbacks {
    /**
     * 随便赋值的一个唯一标识码
     */
    public static final int WRITE_EXTERNAL_STORAGE = 100;
    private final static long time = 24 * 60 * 60 * 1000;  //显示更新间隔  1天
    private static final String TAG = UpdatePresenter.class.getSimpleName();
    SDialog SDdialog;
    private int order;// 新版本号 1
    private String version;//新 版本编号  1.0.2
    private String updatetime; // 最后更新时间
    private String url;// 新版本下载地址
    private int current_order;// 当前版本号
    private String current_version_name;// 当前版本名称
    private String des;// 版本描述
    private Activity context;
    private int count; // 用户取消多少次后不显示 一个版本显示多少次再显示
    private int hascancel;// 用户已经取消的次数
    private String[] params;

    public UpdatePresenter() {
        PackageInfo packageInfo = UpdateVersionUtils.getPackageInfo(MyApplication.getInstance());
        current_order = packageInfo.versionCode;
        current_version_name = packageInfo.versionName;
    }

    public void setToas(boolean toas) {
        IsToas = toas;
    }

    private boolean IsToas;//是否提示

    public UpdatePresenter(Activity ctx, int count) {
        this.context = ctx;
        this.count = count;


        PackageInfo packageInfo = UpdateVersionUtils.getPackageInfo(MyApplication.getInstance());
        current_order = packageInfo.versionCode;
        current_version_name = packageInfo.versionName;
//        sp = ctx.getSharedPreferences("config", Activity.MODE_PRIVATE);
//        last_show_dialog_time = sp.getLong("last_show_dialog_time", 0);// 用户关了之后1天之内不再显示

    }



    public void getVersionInfo() {

        HashMap<String, String> params = new HashMap<>();
        params.put("type", "1");
        ApiClient.postForm(HttpConstants.CHECK_VERSION, params, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (e instanceof UnknownHostException || e instanceof SocketException) {
                    SToast.show(R.string.tip_network_error, Gravity.CENTER);
                    return;
                }
            }

            @Override
            public void onResponse(String response, int id) {

                String res = response;

                try {
                    JSONObject json = new JSONObject(res);

                    if (json.optInt("code", 0) == 0) {
                        SToast.show(json.optString("msg"));
                    } else {
                        json = json.getJSONObject("data");
                        order = Integer.valueOf(json.getString("version_code"));// 版本号 1
                      //  int forceUpdate = json.getInt("force_update");// 强制升级
                        version = json.getString("version_name");//版本遍号  1.0.2
                        updatetime = json.getString("dateline"); // 最后更新时间
                        url = json.getString("urlpath");// 新版本下载地址

//                        url = "http://dl01.new4s.com/app_3.0.4.apk";
//                        des = json.getString("desc");
//                        int applyVersion = json.getInt("applyVersion");// 在此版本前包括此版本必须升级()

//                        hascancel = sp.getInt(version, 0);//记录的取消次数  已版本编号为KEY 存入数据
//                        long t = System.currentTimeMillis() - last_show_dialog_time;
                        if(order>current_order){
                            //服务器版本号大于当前apk版本，判断是否需要强制更新
                            String[] vs = version.split("\\.");
                            String[] cvs = current_version_name.split("\\.");
                            boolean force = false;

                            if(vs.length == cvs.length){
                                if(vs[0].equals(cvs[0]) && vs[1].equals(cvs[1])){
                                    force = false;
                                }else{
                                    force = true;
                                }
                            }else{
                                force = true;
                            }
                            if(force){
                                // 强制升级
                                showforceUpdateDialog();
                            }else{
                                // 有新版本
                                showDialog();
                            }
                        }


//                        if (forceUpdate == 1 && order > current_order) {// 强制升级   1 强制升级  0不强制
//                            showforceUpdateDialog();
//                            return;
//                        }
//
//                        if (order > current_order) {//非强制升级
//                            // 有新版本
//                            showDialog();
//                        }else if (IsToas){
//                            SToast.show("当前已是最新版本");
//                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public void showDialog() {
//        this.context = MyApplication.getInstance().getActivity();
//        if (context==null){
//            return;
//        }
//        SDdialog = ((BaseActivity) context).showTwoBtnDialog("温馨提示", (UpdateVersionUtils.isWifi(context) ? "" : "非wifi下,") + "检测到有新版本,是否前往更新!", R.string.cancel,
//                R.string.update_immediately, false, new SDialog.SDialog2Listener() {
//
//                    @Override
//                    public void onClick(boolean l, View view) {
//                        if (!l) {
//                            // 检测系统下载器是否可用
//                            int state = context.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");
//
//                            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED ||
//                                    state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
//                                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
//                                // 提示下载管理器对话框
//                                showDownloadManger();
//                            } else {
//                                checkPerm();
//                            }
//                        } else {
//                            if (SDdialog != null)
//                                SDdialog.dismiss();
//                        }
//                    }
//
//
//                }, false);
    }


    private void showDownloadManger() {
        ((BaseActivity) context).showTwoBtnDialog(null, "下载管理器未启用，启用后继续下载", R.string.cancel, R.string.go_to_setting,
                false, new SDialog.SDialog2Listener() {
                    @Override
                    public void onClick(boolean l, View view) {
                        if (!l) {  // 打开
                            openDownloadManager();
                        }
                    }
                });
    }


    private void openDownloadManager() {
        try {
            Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + "com.android.providers.downloads"));
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
            context.startActivity(intent);
        }
    }


    // 强制升级dialog
    private void showforceUpdateDialog() {

        ((BaseActivity) context).showTwoBtnDialog("温馨提示", "检测到有新版本,是否前往更新!", R.string.logout_app,
                R.string.update_immediately, false, new SDialog.SDialog2Listener() {

                    @Override
                    public void onClick(boolean l, View view) {
                        if (!l) {
                            int state = context.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");

                            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED ||
                                    state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                                // 提示下载管理器对话框
                                showDownloadManger();
                            } else {
                                checkPerm();
//                                UpdateVersionUtils.loadAPP(MyApplication.getInstance(), url);
//                                ((BaseActivity) context).showLoading("下载中", false);
                            }
                        } else {
//                            MyApplication.getInstance().exit();
                        }
                    }
                }, false);
    }

    /**
     * 检查权限
     */
    @AfterPermissionGranted(WRITE_EXTERNAL_STORAGE)
    private void checkPerm() {
        params = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(context, params)) {
            long downId = UpdateVersionUtils.loadAPP(MyApplication.getInstance(), url);
            if(downId>0){
                listener(downId);
            }
            SToast.makeText(R.string.load_background);
            if (SDdialog != null)
                SDdialog.dismiss();
        } else {
            EasyPermissions.requestPermissions(context, "需要读写本地权限", WRITE_EXTERNAL_STORAGE, params);
        }
    }

    private void listener(final long Id) {
        if(this.context == null)return;
        // 注册广播监听系统的下载完成事件。
        IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                DownloadManager manager = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
                // 这里是通过下面这个方法获取下载的id，
                long ID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                // 这里把传递的id和广播中获取的id进行对比是不是我们下载apk的那个id，如果是的话，就开始获取这个下载的路径
                if (ID == Id) {
                    DownloadManager.Query query = new DownloadManager.Query();
                    query.setFilterById(Id);
                    Cursor cursor = manager.query(query);
                    if (cursor.moveToFirst()){
                        // 获取文件下载路径
                        String fileName = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                        // 如果文件名不为空，说明文件已存在,则进行自动安装apk
                        if (fileName != null){
                            openAPK(fileName);
                        }
                    }
                    cursor.close();
                }
            }
        };
        this.context.registerReceiver(broadcastReceiver, intentFilter);
    }

    private void openAPK(String fileSavePath){
//        if(this.context == null)return;
//        File file=new File(Uri.parse(fileSavePath).getPath());
//        String filePath = file.getAbsolutePath();
//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        Uri data = null;
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//判断版本大于等于7.0
//            // 生成文件的uri，，
//            // 注意 下面参数com.ausee.fileprovider 为apk的包名加上.fileprovider，
//            data = FileProvider.getUriForFile(this.context, HttpConstants.PackageName +".fileprovider", new File(filePath));
//            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);// 给目标应用一个临时授权
//        } else {
//            data = Uri.fromFile(file);
//        }
//        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);// 给目标应用一个临时授权
//        intent.setDataAndType(data, "application/vnd.android.package-archive");
//        this.context.startActivity(intent);
    }

    /**
     * 请求权限成功。
     *
     * @param requestCode
     * @param perms
     */

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
//        if (EasyPermissions.hasPermissions(context, params)) {
//            UpdateVersionUtils.loadAPP(MyApplication.getInstance(), url);
//            SToast.makeText(R.string.load_background);
//            if (SDdialog != null)
//                SDdialog.dismiss();
//        }

    }

    /**
     * 请求权限失败
     *
     * @param requestCode
     * @param perms
     */

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(context, perms)) {
            //这里需要重新设置Rationale和title，否则默认是英文格式
            new AppSettingsDialog.Builder(context)
                    .setRationale("没有该权限，此应用程序可能无法正常工作。打开应用设置屏幕以修改应用权限")
                    .setTitle("必需权限")
                    .build()
                    .show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);

    }
}
